<template>
  <div class="tablePageWarp" id="carListModel" style="padding: 0">
    <div class="listSearchWrap table-page-search-wrapper">
      <a-row :gutter="[8, 16]">
        <a-col
          :xs="12"
          :sm="12"
          :md="12"
          :lg="8"
          :xl="7"
          :xxl="7">
          <province-select
            mode="multiple"
            :maxTagCount="1"
            :default-value="dataSource[dataAdress].queryParam.province"
            style="width: 100%"
            @changeoption="changeOption($event)"
          ></province-select>
        </a-col>
        <a-col
          :xs="12"
          :sm="12"
          :md="6"
          :lg="8"
          :xl="5"
          :xxl="5">
          <a-select
            v-model.trim="dataSource[dataAdress].queryParam.vehicleType"
            style="width: 100%"
            showSearch
            allow-clear
            optionFilterProp="children"
            :filterOption="$commonFun.filterOption"
            :getPopupContainer="getNewtaskPopupContainer"
            :placeholder="$t('pleaseSelect') + $t('vehicleType').toLowerCase()"
          >
            <a-select-option v-for="(item, index) in vehicleTypeOptions" :value="item.id" :key="index">
              {{ $t(item.name) }}
            </a-select-option>
          </a-select>
        </a-col>
        <a-col
          :xs="12"
          :sm="12"
          :md="12"
          :lg="8"
          :xl="6"
          :xxl="6">
          <a-input
            v-model.trim="dataSource[dataAdress].queryParam.vin"
            @keyup.enter="refreshData"
            :placeholder="$t('pleaseInput') + 'VIN'"
          />
        </a-col>
        <a-col
          :xs="24"
          :sm="24"
          :md="14"
          :lg="16"
          :xl="6"
          :xxl="6">
          <div class="searchBtns">
            <a-button @click="refreshData">
              {{ $t('inquiry') }}
            </a-button>
            <a-button
              @click="
                () => {
                  dataSource[dataAdress].queryParam = {}
                  refreshData()
                }
              "
            >
              {{ $t('clear') }}
            </a-button>
          </div>
        </a-col>
      </a-row>
    </div>
    <!-- 已选择车辆 -->
    <div style="padding-bottom: 24px">
      <span
      >{{ $t('selectedVehicles') }}
        {{
          dataSource[dataAdress].isSlefSelect
            ? dataSource[dataAdress].selectCarIds.length
            : dataSource[dataAdress].selectCarTotal
        }}</span
        >
      <a-checkbox style="float: right" @change="changeSelfSelect" :checked="dataSource[dataAdress].isSlefSelect">{{
        $t('customSelect')
      }}</a-checkbox>
    </div>
    <div class="commonTableSty" ref="carList">
      <a-table
        ref="table"
        size="default"
        rowKey="id"
        :components="tableComponents"
        :columns="columns"
        :dataSource="loadData"
        :pagination="pagination"
        :row-selection="
          dataSource[dataAdress].isSlefSelect
            ? { selectedRowKeys: dataSource[dataAdress].selectCarIds, onChange: onSelectChange }
            : null
        "
        :scroll="{ x: 900, y: scrollDomMaxScrollHeight - 70 }"
        @change="handleTableChange"
      >
        <template
          slot-scope="text"
          v-for="column in columns.filter((item) => !item.special)"
          :slot="column.scopedSlots.customRender"
        >
          <table-ellipsis :text="text || '-'" :key="column.dataIndex"></table-ellipsis>
        </template>
        <template slot="vin" slot-scope="text, record">
          <div class="withTextAndTagTd">
            <div class="tdText">
              <table-ellipsis :text="text"></table-ellipsis>
            </div>
            <lock-risk-jump
              :config="{
                lockFlag: record.lockFlag,
                compatibleRisk: 0,
                taskJump: 0,
                query: { taskId: '', vehicleId: record.id },
              }"
            >
            </lock-risk-jump>
          </div>
        </template>
        <template slot="vehicleType" slot-scope="text">
          {{ $t(vehicleTypeObj[text]) }}
        </template>
        <template slot="lastActiveTime" slot-scope="text">
          <table-ellipsis :text="$options.filters.moment(text)"></table-ellipsis>
        </template>
        <template slot="province" slot-scope="text">
          <table-ellipsis :text="$t(text)"></table-ellipsis>
        </template>
      </a-table>
    </div>
  </div>
</template>
<script>
import { mixinScrollLoadData } from '@/utils/mixin'
import ProvinceSelect from '@/views/components/ProvinceSelect'
import TableEllipsis from '@/components/Ellipsis/TableEllipsis'
import { mapState } from 'vuex'
import LockRiskJump from '@/views/components/CustomTag/lockRiskJump.vue'
import { viewChoseCarListColumns } from '../config'
import tableDraggable from '@/utils/tableDraggable'
import { STable } from '@/components'

export default {
  name: 'ViewChoseCarList',
  mixins: [mixinScrollLoadData],
  components: { TableEllipsis, ProvinceSelect, LockRiskJump, STable },
  props: {
    dataAdress: {
      type: String,
      default: 'newTaskData'
    }
  },
  computed: {
    ...mapState({
      dataSource: (state) => state.newTask,
      vehicleTypeOptions: (state) => state.vehicle.types
    }),
    vehicleTypeObj () {
      return this.$store.getters.vehicleTypeObj()
    }
  },
  data () {
    return {
      columns: viewChoseCarListColumns,
      loadData: [],
      pagination: {
        pageSize: 30
      },
      scrollDomRef: 'carList',
      tableComponents: {}
    }
  },
  created () {
    this.tableComponents = tableDraggable(this.columns)
  },
  mounted () {
    this.loadPageData()
  },
  methods: {
    loadPageData () {
      const vm = this
      return new Promise((resolve, reject) => {
        const JnqueryParam = JSON.parse(JSON.stringify(vm.dataSource[vm.dataAdress].queryParam))
        // eslint-disable-next-line no-restricted-syntax
        for (const key in JnqueryParam) {
          if (JnqueryParam[key] === '') {
            JnqueryParam[key] = undefined
          }
        }
        JnqueryParam.modelIds = [vm.dataSource[vm.dataAdress].modelId]
        vm.loadingPageData = true
        vm.$api
          .getVehiclePageData({ pageNo: vm.pagination.current, pageSize: vm.pagination.pageSize, ...JnqueryParam })
          .then((res) => {
            let { data } = res
            if (this.pageCount > 1) {
              data = this.tbData.concat(data)
            }
            this.loadData = data
            this.dataSource[this.dataAdress].selectCarTotal = res.totalCount
            this.totalPage = res.totalPage
            this.pagination = {...this.pagination, total : res.totalCount};
            resolve(res)
          })
          .catch((err) => {
            reject(err)
          })
          .finally(() => {
            vm.loadingPageData = false
          })
      })
    },
    // 是否自定义
    changeSelfSelect (e) {
      this.dataSource[this.dataAdress].isSlefSelect = e.target.checked
    },
    onSelectChange (selectedRowKeys) {
      this.dataSource[this.dataAdress].selectCarIds = selectedRowKeys
    },
    changeOption (val) {
      this.$set(this.dataSource[this.dataAdress].queryParam, 'province', val)
    },
    handleTableChange (pagination, filters, sorter) {
      this.pagination = {...pagination};
      if (sorter && sorter.columnKey) {
        this.sortedInfo = sorter
        if (sorter.order) {
          const orderType = {
            ascend: 'ASC',
            descend: 'DESC'
          }
          this.dataSource[this.dataAdress].queryParam.order = `${sorter.columnKey},${orderType[sorter.order]}`
        } else {
          this.dataSource[this.dataAdress].queryParam.order = null
        }
      }
      this.loadPageData()
    },
    getNewtaskPopupContainer (triggerNode) {
      if (triggerNode) {
        return triggerNode.parentNode
      }
      return document.body
    }
  }
}
</script>
